<template>
  <!-- 搜索区域 -->
  <div style="height: 10vh; background-color: #fff; padding: 10px 20px;">
    <el-card style="height: 100%;">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef">
        <el-form-item label="名称" prop="parkName">
          <el-select v-model="searchForm.parkName" placeholder="请选择停车场名称" style="width: 18vh" filterable clearable>
            <el-option v-for="park in parkData.parkNames" :key="park.value" :label="park.label" :value="park.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-select v-model="searchForm.address" placeholder="请选择停车场地址" style="width: 18vh" filterable clearable>
            <el-option v-for="park in parkData.addresses" :key="park.value" :label="park.label" :value="park.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系号码" prop="contactPhone">
          <el-select v-model="searchForm.contactPhone" placeholder="请选择联系号码" style="width: 18vh" filterable clearable>
            <el-option v-for="phone in parkData.contactPhones" :key="phone.value" :label="phone.label" :value="phone.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="searchForm.status" placeholder="请选择状态" style="width: 18vh" filterable clearable>
            <el-option v-for="status in parkData.statuses" :key="status.value" :label="status.label" :value="status.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-form :inline="true">
        <el-form-item>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" :loading="loading" @click="queryForm">查询</el-button>
          <el-button type="primary" @click="newDialog">新建</el-button>
          <el-button
              :disabled="selectedRows.length === 0"
              :style="{ backgroundColor: selectedRows.length === 0 ? '#ffcccc' : '#ff4d4f', color: '#fff' }"
              @click="batchDelete" > 删除
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>

  <!-- 弹窗 -->
  <el-dialog :title="dialogTitle" v-model="dialogVisible" width="40vh">
    <el-form
        label-width="10vh"
        label-position="left"
        :model="dialogForm"
        ref="dialogFormRef"
        :rules="dialogRules"
        class="dialog-form"
    >
      <el-row style="display: flex; flex-direction: column; align-items: center;" :gutter="10">
        <el-col :span="24">
          <el-form-item label="停车场名称：" prop="parkName">
            <el-input placeholder="请输入内容" v-model="dialogForm.parkName" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="停车场地址：" prop="address">
            <el-input placeholder="请输入内容" v-model="dialogForm.address" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="联系号码：" prop="contactPhone">
            <el-input placeholder="请输入联系号码" v-model="dialogForm.contactPhone" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="车位数：" prop="totalSpace">
            <el-input placeholder="请输入内容" v-model="dialogForm.totalSpace" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="临停计费规则：" prop="billRule">
            <el-select v-model="dialogForm.billRule" placeholder="请选择临停计费规则" filterable>
              <el-option label="免费停车" value="免费停车" :key="'免费停车'">
                <el-tooltip content="选择此项表示停车场不收取停车费用" placement="top">
                  <span>免费停车</span>
                </el-tooltip>
              </el-option>
              <el-option
                  v-for="rule in billRules"
                  :key="rule.ruleNum"
                  :label="rule.ruleName"
                  :value="rule.ruleName"
              >
                <el-tooltip :content="getRuleTooltip(rule)" placement="top">
                  <span>{{ rule.ruleName }}</span>
                </el-tooltip>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div style="display: flex; justify-content: center; gap: 20px;">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveDialog">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 表格和分页区域 -->
  <el-card style="margin: 20px; height: 70vh; display: flex; flex-direction: column;">
    <!-- 表格容器 -->
    <div class="table-container">
      <el-table
          :data="showList"
          border
          v-loading="loading"
          @selection-change="handleSelectionChange"
          ref="tableRef"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="parkName" label="名称" align="center" />
        <el-table-column prop="address" label="地址" align="center" />
        <el-table-column prop="contactPhone" label="联系号码" align="center" />
        <el-table-column prop="totalSpace" label="总车位数" align="center" />
        <el-table-column prop="occupySpace" label="占用车位数" align="center" />
        <el-table-column prop="billRule" label="临停计费规则" align="center">
          <template #default="scope">
            <el-tooltip :content="getRuleTooltip(getBillRuleDetails(scope.row.billRule))" placement="top">
              <span>{{ scope.row.billRule || '未设置' }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center" />
        <el-table-column prop="createTime" label="创建时间" align="center" />
        <el-table-column prop="updateTime" label="更新时间" align="center" />
        <el-table-column label="操作" align="center" width="150">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="editParking(scope.row)">编辑</el-button>
            <el-button link type="danger" size="small" @click="deleteParking(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页容器 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
      />
    </div>
  </el-card>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

const API_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:9999'; // 默认后端地址

// 搜索表单
const searchFormRef = ref(null);
const searchForm = ref({ });

// 表格数据和分页
const showList = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);

// 搜索选项数据
const parkData = ref({
  parkNames: [],
  addresses: [],
  contactPhones: [],
  statuses: [
    { label: '正常', value: '正常' },
    { label: '拥堵', value: '拥堵' }
  ]
});

// 计费规则选项
const billRules = ref([]);

// 弹窗控制
const dialogVisible = ref(false);
const dialogTitle = ref('新增停车场');
const dialogFormRef = ref(null);
const dialogForm = ref({
  id: null,
  parkName: '',
  address: '',
  contactPhone: '',
  totalSpace: '',
  status: '正常',
  occupySpace: '0',
  billRule: '免费停车',
  createTime: '',
  updateTime: ''
});

// 弹窗校验规则
const dialogRules = ref({
  parkName: [
    { required: true, message: '请输入停车场名称', trigger: 'blur' },
    {
      validator: async (rule, value, callback) => {
        if (!value || value.trim() === '') {
          callback(new Error('请输入停车场名称'));
          return;
        }
        const response = await axios.get(`${API_URL}/v1/parklot/check-duplicate`, {
          params: { parkName: value, id: dialogForm.value.id }
        });
        const data = response.data;
        if (data.code === 2000) {
          if (data.isDuplicate) {
            callback(new Error('停车场名称已存在'));
          } else {
            callback();
          }
        } else if (data.code === 4000) {
          callback(new Error(data.message));
        } else {
          callback(new Error('校验失败: ' + (data.message || '未知错误')));
        }
      },
      trigger: 'blur'
    }
  ],
  address: [
    { required: true, message: '请输入停车场地址', trigger: 'blur' },
    {
      validator: async (rule, value, callback) => {
        if (!value || value.trim() === '') {
          callback(new Error('请输入停车场地址'));
          return;
        }
        const response = await axios.get(`${API_URL}/v1/parklot/check-duplicate`, {
          params: { address: value, id: dialogForm.value.id }
        });
        const data = response.data;
        if (data.code === 2000) {
          if (data.isDuplicate) {
            callback(new Error('停车场地址已存在'));
          } else {
            callback();
          }
        } else if (data.code === 4000) {
          callback(new Error(data.message));
        } else {
          callback(new Error('校验失败: ' + (data.message || '未知错误')));
        }
      },
      trigger: 'blur'
    }
  ],
  contactPhone: [
    { required: true, message: '请输入联系号码', trigger: 'change' }
  ],
  totalSpace: [
    { required: true, message: '请输入车位数', trigger: 'blur' },
    { type: 'number', message: '车位数必须为数字', transform: (value) => Number(value) }
  ],
  billRule: [
    { required: true, message: '请选择临停计费规则', trigger: 'change' }
  ]
});

// 多选框相关
const selectedRows = ref([]);
const tableRef = ref(null);

// 查询停车场列表（支持分页）
const queryForm = async () => {
  loading.value = true;
  const params = {
    ...searchForm.value,
    page: currentPage.value,
    size: pageSize.value
  };
  const { data } = await axios.get(`${API_URL}/v1/parklot/select`, { params });
  if (data.code === 2000) {
    showList.value = data.response || [];
    total.value = data.total || 0;
    ElMessage.success('数据加载成功');
  } else {
    ElMessage.error(`数据加载失败: ${data.response?.message || '未知错误'}`);
    showList.value = [];
    total.value = 0;
  }
  loading.value = false;
};

// 获取所有停车场数据用于搜索选项
const fetchAllParkingOptions = async () => {
  const { data } = await axios.get(`${API_URL}/v1/parklot/select`, { params: { size: 10000 } });
  if (data.code === 2000) {
    updateSearchOptions(data.response);
  } else {
    ElMessage.error('停车场选项加载失败');
  }
};

// 更新搜索区域的下拉选项
const updateSearchOptions = (parks) => {
  const phoneMap = new Map();
  parks.forEach(park => {
    if (park.contactPhone) phoneMap.set(park.contactPhone, park.contactPhone);
  });
  parkData.value.contactPhones = Array.from(phoneMap, ([value, label]) => ({ value, label }));
  parkData.value.parkNames = parks.map(park => ({ label: park.parkName, value: park.parkName }));
  parkData.value.addresses = parks.map(park => ({ label: park.address, value: park.address }));
};

// 获取计费规则选项
const fetchBillRules = async () => {
  const { data } = await axios.get(`${API_URL}/v1/bill-temp-rule/select`);
  if (data.code === 2000) {
    billRules.value = data.response;
  } else {
    ElMessage.error('计费规则加载失败');
  }
};

// 获取计费规则详情的工具提示内容
const getRuleTooltip = (rule) => {
  if (!rule || rule === '免费停车') return '免费停车，不收取停车费用';
  return `免费时长: ${rule.freeTime}分钟, 每小时价格: ${rule.hourlyBilling}元, 24小时上限: ${rule.billLimit}元, 计费方式: ${rule.billMode}, 计费时段: ${rule.startTime}-${rule.endTime}`;
};

// 根据规则名称获取详情
const getBillRuleDetails = (ruleName) => {
  if (ruleName === '免费停车' || !ruleName) return '免费停车';
  return billRules.value.find(rule => rule.ruleName === ruleName) || null;
};

// 重置搜索条件
const resetForm = () => {
  searchFormRef.value.resetFields();
  currentPage.value = 1;
  ElMessage.success('已重置筛选条件');
  queryForm();
};

// 新建停车场
const newDialog = () => {
  dialogVisible.value = true;
  dialogTitle.value = '新增停车场';
  dialogForm.value = {
    id: null,
    parkName: '',
    address: '',
    contactPhone: '',
    totalSpace: '',
    status: '正常',
    occupySpace: '0',
    billRule: '免费停车'
  };
};


// 关闭弹窗
const closeDialog = () => {
  ElMessageBox.confirm('您确认要关闭本弹窗吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
      .then(() => {
        dialogVisible.value = false;
      })
      .catch(() => {});
};

// 保存停车场
const saveDialog = async () => {
  await dialogFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请检查输入项');
      return;
    }

    const saveData = { ...dialogForm.value };
    const url = saveData.id ? `${API_URL}/v1/parklot/update` : `${API_URL}/v1/parklot/insert`;
    const method = saveData.id ? 'put' : 'post';
    const { data } = await axios({ method, url, data: saveData });

    if (data.code === 2000) {
      ElMessage.success(saveData.id ? '更新成功' : '新建成功');
      dialogVisible.value = false;
      await queryForm();
      await fetchAllParkingOptions();
      await logOperation('停车场管理', `${saveData.id ? '更新' : '新建'}停车场 ${saveData.parkName}`);
    } else {
      ElMessage.error(`保存失败: ${data.response?.message || '未知错误'}`);
    }
  });
};

// 编辑停车场
const editParking = (row) => {
  dialogTitle.value = '编辑停车场';
  dialogForm.value = { ...row, billRule: row.billRule || '免费停车' };
  console.log('Editing park ID:', dialogForm.value.id); // 调试输出
  dialogVisible.value = true;
};

// 处理多选框变化
const handleSelectionChange = (val) => {
  selectedRows.value = val;
};

// 抽象出的删除方法，支持单条和批量删除
const deleteParkings = async (rows) => {
  const isBatch = Array.isArray(rows);
  const count = isBatch ? rows.length : 1;
  const ids = isBatch ? rows.map(row => row.id) : [rows.id];
  const confirmMessage = isBatch
      ? `您确认要删除 ${count} 个停车场吗?`
      : '您确认要删除此停车场吗?';

  await ElMessageBox.confirm(confirmMessage, '删除确认', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  });

  const url = isBatch ? `${API_URL}/v1/parklot/batchDelete` : `${API_URL}/v1/parklot/delete/${ids[0]}`;
  const method = isBatch ? 'post' : 'delete';
  const requestData = isBatch ? { ids } : null;

  const { data } = await axios({ method, url, data: requestData });

  if (data.code === 2000) {
    ElMessage.success(isBatch ? '批量删除成功' : '删除成功');
    await queryForm();
    await fetchAllParkingOptions();
    const logRows = isBatch ? rows : [rows];
    for (const row of logRows) {
      await logOperation('停车场管理', `删除停车场 ${row.parkName}`);
    }
    if (isBatch) {
      selectedRows.value = [];
      tableRef.value.clearSelection();
    }
  } else {
    ElMessage.error(`删除失败: ${data.response?.message || '未知错误'}`);
  }
};

// 删除单个停车场
const deleteParking = async (row) => {
  await deleteParkings(row);
};

// 批量删除
const batchDelete = async () => {
  if (selectedRows.value.length === 0) return;
  await deleteParkings(selectedRows.value);
};

// 分页事件处理
const handleCurrentChange = (val) => {
  currentPage.value = val;
  queryForm();
};

// 页面加载时获取数据
onMounted(async () => {
  await fetchAllParkingOptions();
  await fetchBillRules();
  await queryForm();
});
</script>

<style scoped>
.dialog-form :deep(.el-input) {
  width: 20vh;
}
.dialog-form :deep(.el-select) {
  width: 20vh;
}

/* 表格容器样式 */
.table-container {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 60px; /* 预留分页空间 */
}

/* 分页容器样式 */
.pagination-container {
  padding: 10px 20px;
  text-align: center;
  background-color: #fff;
  min-height: 60px; /* 确保分页区域有足够高度 */
}
</style>